<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true"><block slot="backText">返回</block><block slot="content">聊天</block></cu-custom>
		
		<unicloud-db ref='udb'  :manual='true' v-slot:default="{data, loading, error, options}" collection="chat-record">
			<view v-if="error">{{error.message}}</view>
			<view v-else>
				<view class="cu-chat">
					<view class="item-list" v-for="(item,i) in data" :key='i'>

						<view class="cu-item " :class="item._self?'self':'' ">
							<view v-if="!item._self" class="cu-avatar radius" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big107000.jpg);"></view>
							<view class="main">
								<view class="content shadow">
									<text>{{item.content}}</text>
								</view>
							</view>
							<view v-if="item._self" class="cu-avatar radius" :style="{'background-image':'url({'+userinfo.avatarUrl+'})'}" ></view>
							<view class="date">{{item.time}}</view>
						</view>
						
					</view>
				</view>
			</view>
		</unicloud-db>
		
		

		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<view class="action">
				<text class="cuIcon-sound text-grey"></text>
			</view>
			<input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"
			 @focus="InputFocus" @blur="InputBlur"></input>
			<view class="action">
				<text class="cuIcon-emojifill text-grey"></text>
			</view>
			<button @click="sendMsg" class="cu-btn bg-green shadow">发送</button>
		</view>

	</view>
</template>

<script>
	import {getDate} from '../../../utils/utils.js'
	export default {
		data() {
			return {
				InputBottom: 0,
				userinfo:{},
				db:null,
				value:''
			};
		},
		methods: {
			async sendMsg(){
				console.log(this.value);
				this.createChat()

				const data=await	uni.request({
					url:'http://api.tianapi.com/txapi/robot/index',
					method:'GET',
					data:{
						key:'1a162a6b0fec66a258dc8f80a8c9cfdb',
						question:this.value,
						uniqueid:this.userinfo.openid,
						mode:0,
					}
				})
				console.log(data[1].data.newslist);
				let list=data[1].data.newslist
				if(list.length>0){
					this.createChat(list[0].reply,false)
				}
				
			},
			createChat(value,_self=true){
				let obj={
					openid:this.userinfo.openid,
					content:value||this.value,
					time:getDate(),
					_self
				}
				console.log(obj);
				this.operationDB(obj)
				
			},
			operationDB(obj){
				this.db.collection('chat-record').add(obj);
				this.$refs.udb.loadData({
				    clear: true
				})
			},
			
			
			InputFocus(e) {
				this.InputBottom = e.detail.height
				this.value=e.detail.value
			},
			InputBlur(e) {
				this.InputBottom = 0;
				this.value=e.detail.value
			}
		},
		onLoad() {
			this.userinfo = uni.getStorageSync('userInfo');
			this.db = uniCloud.database();
			console.log(this.userinfo);
		},
		onReady() {
			this.$refs.udb.loadData()
		}
	}
</script>

<style>
page{
  padding-bottom: 100upx;
}
</style>
